﻿namespace WebPacker.Tests.Packs.Watchers
{
	using System;
	using System.Threading;
	using NUnit.Framework;
	using WebPacker.Packs.Resources;
	using WebPacker.Packs.Watchers;

	[TestFixture]
	public class RemoteWatcherTest : ResourceWatcherBaseTest
	{
		private const string Category = "remoteMonitor";
		private string testFilePath1 = TestHelper.GetSamplePath("test1.js", Category);
		private string testFilePath2 = TestHelper.GetSamplePath("test2.js", Category);
		private string testFileUrl1;
		private string testFileUrl2;

		[SetUp]
		public void PrepareSampleFiles()
		{
			TestHelper.PrepareSampleFiles(new string[] { "test1.js", "test2.js" }, Category);
			testFileUrl1 = TestHelper.GetFileUri(testFilePath1);
			testFileUrl2 = TestHelper.GetFileUri(testFilePath2);
		}

		[Test]
		public void ChangedTest()
		{
			var signal = false;

			using (var monitor = new RemoteWatcher())
			{
				monitor.MonitoringInterval = 100;

				var resource = new RemoteResource(testFileUrl1);
				Exception testException = null;

				monitor.Add(resource);
				resource.Update();

				monitor.Changed += (sender, ea) =>
				{
					try
					{
						Assert.AreEqual(monitor, sender);
						Assert.AreEqual(resource.Name, ea.ResourceName);
						signal = true;
					}
					catch (Exception e)
					{
						testException = e;
					}
				};

				ModifyFile(testFilePath1);
				Thread.Sleep(500);

				if (testException != null)
				{
					throw testException;
				}

				Assert.IsTrue(signal);
			}
		}

		protected override IResourceWatcher GetMonitor()
		{
			return new RemoteWatcher();
		}

		protected override IResource GetTestResource()
		{
			return new RemoteResource(testFileUrl1);
		}

		protected override IResource[] GetTestResources()
		{
			return new IResource[] { new RemoteResource(testFileUrl1), new RemoteResource(testFileUrl2) };
		}

		protected override IResource GetNotAcceptableResource()
		{
			return new FileResource(testFilePath1);
		}
	}
}
